import 'dart:async';

import 'package:cunyutech_flutter_core/cunyutech_flutter_core.dart';
import 'package:cunyutech_flutter_ui/src/dialog/main.dart';
import 'package:cunyutech_flutter_ui/src/theme/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

class CYRequestLogItem extends StatefulWidget {
  CYRequestLogItem({ Key key, this.log }) : super(key: key);

  final CYRequestLog log;

  @override
  _CYRequestLogItemState createState() => _CYRequestLogItemState();
}

class _CYRequestLogItemState extends State<CYRequestLogItem> {

  bool expand = false;

  handleCopy() {
    RequestOptions request = widget.log.request;
    ResponseResult response = widget.log.response;
    final List<String> requestBody = [];
    request.body.forEach((String key, dynamic value){
      requestBody.add("[$key]${value.toString()}\n");
    });
    List<String> list = []
      ..addAll([
        request.method.toUpperCase(), "\t", request.path, "\n",
      ])
      ..add("请求分析\n")
      ..addAll([
        "[start]${CYDateFormat.toZone8StringFromUtc(response.startTime)}\n",
        "[end]${CYDateFormat.toZone8StringFromUtc(response.endTime)}\n",
        "[duration]${response.time}ms\n",
        "[decode]${response.decodeTime}ms\n",
      ])
      ..add("请求参数\n")
      ..addAll(requestBody)
      ..add("请求结果\n")
      ..addAll([
        "[code]${response.code.toString()}\n",
        "[message]${response.message}\n",
        "[data]${response.data?.toString()}\n",
      ])
    ;
    ClipboardData data = new ClipboardData(text: list.join(""));
    Clipboard.setData(data);
    showToast(msg: "复制成功");
  }

  @override
  Widget build(BuildContext context) {
    RequestOptions request = widget.log.request;
    ResponseResult response = widget.log.response;

    var cs = CYThemeData.of(context);

    final List<TextSpan> requestBody = [];
    request.body.forEach((String key, dynamic value){
      requestBody.add(
        TextSpan(
          style: TextStyle(),
          children: [
            TextSpan(text: "[$key]", style: TextStyle(color: cs.femaleColor)),
            TextSpan(text: value.toString()),
            TextSpan(text: "\n"),
          ]
        ),
      );
    });
    final List<TextSpan> responseBody = [
      TextSpan(
        style: TextStyle(),
        children: [
          TextSpan(text: "[code]", style: TextStyle(color: cs.femaleColor)),
          TextSpan(text: response.code.toString()),
          TextSpan(text: "\n"),
          TextSpan(text: "[message]", style: TextStyle(color: cs.femaleColor)),
          TextSpan(text: response.message),
          TextSpan(text: "\n"),
          TextSpan(text: "[data]", style: TextStyle(color: cs.femaleColor)),
          TextSpan(text: response.data?.toString()),
          TextSpan(text: "\n"),
        ]
      ),
    ];

    final List<TextSpan> other = [
      TextSpan(
        style: TextStyle(),
        children: [
          TextSpan(text: "[start]", style: TextStyle(color: cs.femaleColor)),
          TextSpan(text: "${CYDateFormat.toZone8StringFromUtc(response.startTime)}"),
          TextSpan(text: "\n"),
          TextSpan(text: "[end]", style: TextStyle(color: cs.femaleColor)),
          TextSpan(text: "${CYDateFormat.toZone8StringFromUtc(response.endTime)}"),
          TextSpan(text: "\n"),
          TextSpan(text: "[duration]", style: TextStyle(color: cs.femaleColor)),
          TextSpan(text: "${response.time}ms"),
          TextSpan(text: "\n"),
          TextSpan(text: "[decode]", style: TextStyle(color: cs.femaleColor)),
          TextSpan(text: "${response.decodeTime}ms"),
          TextSpan(text: "\n"),
        ]
      ),
    ];

    return Container(
      child: Column(
        children: <Widget>[
          GestureDetector(
            onLongPress: handleCopy,
            onTap: () {
              setState((){
                expand = !expand;
              });
            },
            child:
            Container(
              decoration: BoxDecoration(
                color: Colors.black,
                border: Border(bottom: BorderSide(color: cs.darkForeColorSystem.borderColor))
              ),
              height: CYHeight.Default,
              alignment: Alignment.centerLeft,
              child: RichText(
                textAlign: TextAlign.left,
                text: TextSpan(
                  style: TextStyle(color: Colors.white, fontSize: CYFontSize.Small),
                  children: [
                    TextSpan(text: "\t"),
                    TextSpan(
                      text: request.method.toUpperCase(),
                      style: TextStyle(
                        color: request.method == "get" ? cs.secondaryColor : cs.warningColor
                      )
                    ),
                    TextSpan(text: "\t"),
                    TextSpan(
                      text: request.path,
                      style: TextStyle(
                        color: response.code != 200 ? cs.failColor : cs.successColor
                      )
                    ),
                  ]
                ),
              )
            ),
          ),
          Container(
            child: expand == true ? Container(
              color: Colors.black.withOpacity(0.9),
              child: Column(
                children: [
                  RichText(
                    text: TextSpan(
                      style: TextStyle(color: Colors.white, fontSize: CYFontSize.Small),
                      children: []
                        ..add(TextSpan(text: "请求分析\n", style: TextStyle(fontWeight: FontWeight.w600, color: cs.darkForeColorSystem.secondaryColor)))
                        ..addAll(other)
                        ..add(TextSpan(text: "请求参数\n", style: TextStyle(fontWeight: FontWeight.w600, color: cs.darkForeColorSystem.secondaryColor)))
                        ..addAll(requestBody)
                        ..add(TextSpan(text: "请求结果\n", style: TextStyle(fontWeight: FontWeight.w600, color: cs.darkForeColorSystem.secondaryColor)))
                        ..addAll(responseBody)
                    )
                  )
                ]
              ),
            ) : null
          )
        ],
      ),
    );
  }
}

class WebApiConsole extends StatefulWidget {
  WebApiConsole({Key key}) : super(key: key);

  @override
  _WebApiConsoleState createState() => _WebApiConsoleState();
}

class _WebApiConsoleState extends State<WebApiConsole> {
  StreamSubscription<CYRequestLog> subscription;
  @override
  void initState() {
    subscription = CYRequest.eventBus.on<CYRequestLog>().listen(this.handleAddData);
    super.initState();  
  }

  @override
  void dispose() { 
    if(subscription != null) subscription.cancel();
    super.dispose();
  }

  handleAddData(CYRequestLog log) {
    setState(() {
      children.add(CYRequestLogItem(key: Key(log.response.startTime.toString()), log: log));
    });
  }

  List<Widget> children = [];

  @override
  Widget build(BuildContext context) {
    return Container(
       width: 320,
       height: 300,
       color: Colors.black,
       child: Column(
          children: [
            Container(
              height: 20,
              color: Colors.white70,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container( width: 44 ),
                  Text("接口打印", style: TextStyle(fontSize: 10, color: Colors.black45),),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        children.clear();
                      });
                    },
                    child: Container(
                      width: 44,
                      alignment: Alignment.center,
                      child: Text("清除", style: TextStyle(fontSize: 10, color: Colors.black45),),
                    ) 
                  )
                ],
              ) 
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Column(children: children.reversed.toList())
              )
            )
          ]
        ),
    );
  }
}